package com.cal.utms.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.cal.utms.entity.SeqGen;

public class Sequence {

	public String getNextValue(String sequence) {
		String nextVal = "0000000000";
		Session session = HibernateUtil.getSession().openSession();
		SeqGen seqGen = null;
		Transaction tx = null;
		int beginIndex;
		int intNextVal;
		try {
			tx = session.beginTransaction();
			seqGen = (SeqGen) session.get(SeqGen.class, sequence);
			intNextVal = seqGen.getValue() + 1;
			seqGen.setValue(intNextVal);
			session.update(seqGen);
			tx.commit();
			beginIndex = (intNextVal + "").length();
			nextVal = nextVal + intNextVal;
			nextVal = nextVal.substring(beginIndex);
			return nextVal;
		} catch (HibernateException he) {
			System.out.println("Error: Getting Sequence: " + he.getMessage());
			he.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}

}
